package com.glory.brepda.activity.mfg;

import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.GoldenResultAdapter;
import com.glory.brepda.adapter.GoldenSmapleAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EqpEntity;
import com.glory.brepda.entity.EqpInfoEntity;
import com.glory.brepda.entity.GoldenSampleTestDataEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.PageInfoEntity;
import com.glory.brepda.entity.ParametersEntity;
import com.glory.brepda.entity.request.BaseRequest;
import com.glory.brepda.entity.request.HeaderBean;
import com.glory.brepda.entity.request.RequestBean;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.OkHttpClient;

public class GoldenSmapleActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.flMark)
    FrameLayout flMark;
    @BindView(R.id.ivMark)
    ImageView ivMark;
    @BindView(R.id.rvGoldenSmapleList)
    RecyclerView rvGoldenSmapleList;
    @BindView(R.id.rvGoldenResultSmapleList)
    RecyclerView rvGoldenResultSmapleList;
    @BindView(R.id.etEqpID)
    FreeUI_ClearEditText etEqpID;
    @BindView(R.id.etTestRecID)
    FreeUI_ClearEditText etTestRecID;
    @BindView(R.id.tvEqpType)
    TextView tvEqpType;
    @BindView(R.id.tvCustomerCode)
    TextView tvCustomerCode;
    @BindView(R.id.tvWaferMaterialDesc)
    TextView tvWaferMaterialDesc;
    @BindView(R.id.tvCircuitName)
    TextView tvCircuitName;
    @BindView(R.id.tvMark)
    TextView tvMark;


    private FreeUI_GeneralPop mMarkPop;
    private ArrayList<String> markList = new ArrayList<>();

    private ArrayList<String> testDataList = new ArrayList<>();
    private GoldenSmapleAdapter mGoldenSmapleAdapter;
    private com.glory.brepda.adapter.GoldenResultAdapter mGoldenResultAdapter;
    private ArrayList<GoldenSampleTestDataEntity.DataEntity> dataEntities;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_golden_smaple;
    }

    @Override
    protected void initView() {
        tvTitle.setText("GoldenSample验证");
        setMainLayout(llMain);

        initEdit(etEqpID, new editTextListener() {
            @Override
            public void onTextChangeListener(String s) {
                FreeUI_EntityCallBack<BaseResponseBean<EqpEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EqpEntity>>
                        (new TypeToken<BaseResponseBean<EqpEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<EqpEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            EqpEntity eqpEntity = response.body().getResponse().getBody();
                            tvEqpType.setText(eqpEntity.getEquipment().getEqptype());
                            etLot.requestFocus();
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<EqpEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "EQUIPMENTID");
                    }
                };

                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", "EQPBYID");
                EqpEntity.EquipmentlistBean equipmentlistBean = new EqpEntity.EquipmentlistBean();
                equipmentlistBean.setEquipmentid(s);
                map.add("EQUIPMENT", new JsonParser().parse(new Gson().toJson(equipmentlistBean)).getAsJsonObject());
                NetUtils.requestPostNet("IF.BREQUERYEQP", "Common", GoldenSmapleActivity.this, map, callBack);
            }
        });

        initEdit(etLot, s -> {
            if(etEqpID.getText().toString().isEmpty()){
                showToast("请先扫描设备ID",false);
                return;
            }
            //获取lot信息
            LotUtils.searchLotInfo(GoldenSmapleActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    tvCustomerCode.setText(response.getLOT().getCUSTOMERCODE());
                    tvWaferMaterialDesc.setText(response.getCHIPNAME());
                    tvCircuitName.setText(response.getPRODUCTMODEL());
                    getTestRecList();
                    initData();
                    rvGoldenSmapleList.setVisibility(View.VISIBLE);
                    rvGoldenResultSmapleList.setVisibility(View.GONE);
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });

        initEdit(etTestRecID, s ->{
            FreeUI_EntityCallBack<BaseResponseBean<GoldenSampleTestDataEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<GoldenSampleTestDataEntity>>
                    (new TypeToken<BaseResponseBean<GoldenSampleTestDataEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<GoldenSampleTestDataEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                        ArrayList<String> strings = new ArrayList<>();
                        for (GoldenSampleTestDataEntity.GoldenSampleCfgEntity data:response.body().getResponse().getBody().getGoldenSampleCfgs()){
                            strings.add(data.getSampleNO());
                        }
                        mGoldenSmapleAdapter.setDataList(strings);
                        mGoldenSmapleAdapter.setNewData(response.body().getResponse().getBody().getDatas());
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<GoldenSampleTestDataEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(),"GetGoldenSampleTestData");
                }
            };
            JsonObject map = new JsonObject();
            map.addProperty("TestRecID", s);
            NetUtils.requestPostNet("IF.GetGoldenSampleTestData", "GetGoldenSampleTestData", this, map, callBack);

        });
    }


    private void getTestRecList(){

        FreeUI_EntityCallBack<BaseResponseBean<GoldenSampleTestDataEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<GoldenSampleTestDataEntity>>
                (new TypeToken<BaseResponseBean<GoldenSampleTestDataEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<GoldenSampleTestDataEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
//                    ArrayList<String> strings = new ArrayList<>();
//                    for (GoldenSampleTestDataEntity.GoldenSampleCfgEntity data:response.body().getResponse().getBody().getGoldenSampleCfgs()){
//                        strings.add(data.getSampleNO());
//                    }
//                    mGoldenSmapleAdapter.setDataList(strings);
//                    mGoldenSmapleAdapter.setNewData(response.body().getResponse().getBody().getDatas());
                    if(dataEntities!=null){
                        dataEntities.clear();
                    }
                    dataEntities = response.body().getResponse().getBody().getData();
                    testDataList.clear();
//                    for (GoldenSampleTestDataEntity.DataEntity datum : dataEntities) {
//                        datum.setTestRecId(datum.getTestRecId()+datum.getTestSeq());
//                        testDataList.add(datum.getTestType());
//                        //testDataList.add(datum.getTesterRupt());
//                    }
                    for(int i=0;i<dataEntities.size();i++){
//                        String newtesttype=dataEntities.get(i).getTestType()+dataEntities.get(i).getTestSeq();
//                        int newtestseq=dataEntities.get(i).getTestSeq();
//                        ArrayList<GoldenSampleTestDataEntity.DataEntity> dataEntities1=new ArrayList<>();
//                        GoldenSampleTestDataEntity.DataEntity data = new GoldenSampleTestDataEntity.DataEntity();
//                        data.setTestType(newtesttype);
//                        data.setTestRecId(dataEntities.get(i).getTestRecId());
//                        data.setTestSeq(newtestseq);
//                        dataEntities1.add(data);
//                        dataEntities.set(0,dataEntities1.get(0));
                        dataEntities.get(i).setTestType(dataEntities.get(i).getTestType()+dataEntities.get(i).getTestSeq());
                        testDataList.add(dataEntities.get(i).getTestType());
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<GoldenSampleTestDataEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"getTestData");
            }
        };


        JsonObject map = new JsonObject();
        PageInfoEntity pageInfo = new PageInfoEntity();
        ParametersEntity parameters = new ParametersEntity(etLot.getText().toString(),etEqpID.getText().toString());
        map.add("PageInfo", new JsonParser().parse(new Gson().toJson(pageInfo)).getAsJsonObject());
        map.add("Parameters", new JsonParser().parse(new Gson().toJson(parameters)).getAsJsonObject());
        NetUtils.requestPostNet("getTestData", "GetTestData", this, map, callBack);
    }
    @Override
    protected void initData() {
        initRecyclerView(rvGoldenSmapleList, this);
        mGoldenSmapleAdapter = new GoldenSmapleAdapter(null,this,getSupportFragmentManager());
        mGoldenSmapleAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mGoldenSmapleAdapter.isFirstOnly(true);
        rvGoldenSmapleList.setAdapter(mGoldenSmapleAdapter);

        initRecyclerView(rvGoldenResultSmapleList,this);
        mGoldenResultAdapter = new GoldenResultAdapter(null,this,getSupportFragmentManager());
        mGoldenResultAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mGoldenResultAdapter.isFirstOnly(true);
        rvGoldenResultSmapleList.setAdapter(mGoldenResultAdapter);

    }

    @OnClick({R.id.tvBaseSubmit,R.id.flMark})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvBaseSubmit:
                if (actionControl("Submit11")) {
                    return;
                }

                if (getText(etLot).equals("")){
                    showToast("批次号不能为空",false);
                    return;
                }



                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
                        FreeUI_EntityCallBack<BaseResponseBean<GoldenSampleTestDataEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<GoldenSampleTestDataEntity>>
                                (new TypeToken<BaseResponseBean<GoldenSampleTestDataEntity>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<GoldenSampleTestDataEntity>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                    rvGoldenSmapleList.setVisibility(View.GONE);
                                    rvGoldenResultSmapleList.setVisibility(View.VISIBLE);
                                    mGoldenResultAdapter.setDataList(response.body().getResponse().getBody().getResultCode()+";\n"+response.body().getResponse().getBody().getResultInfo()+";\n");
                                    mGoldenResultAdapter.setNewData((List<GoldenSampleTestDataEntity.DataEntity>)response.body().getResponse().getBody().getDatas());
                                    showToast("提交成功", true);
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<GoldenSampleTestDataEntity>> response) {
                                super.onError(response);
                                loadError(response.getException(), "GoldenSampleTestDataCheck");
                            }
                        };

                        JsonObject map = new JsonObject();

                        for(int i=0;i<mGoldenSmapleAdapter.getData().size();i++){
                            if(mGoldenSmapleAdapter.getData().get(i).getDataStatus()=="0"){
                                mGoldenSmapleAdapter.remove(i);
                                i--;
                            }
                        }

                        map.add("Datas", new JsonParser().parse(new Gson().toJson(mGoldenSmapleAdapter.getData())).getAsJsonArray());
                        for (GoldenSampleTestDataEntity.DataEntity dataEntity : dataEntities) {
                            if (dataEntity.getTestType().equals(tvMark.getText().toString())) {
                                map.addProperty("TestRecID", dataEntity.getTestRecId());
                            }
                        }

                        OkHttpClient.Builder builder = new OkHttpClient.Builder();
                        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
                        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
                        loggingInterceptor.setColorLevel(java.util.logging.Level.INFO);
                        builder.addInterceptor(loggingInterceptor);
                        builder.connectTimeout(240 * 1000L, TimeUnit.MILLISECONDS);
                        builder.readTimeout(240 * 1000L, TimeUnit.MILLISECONDS);
                        builder.writeTimeout(240 * 1000L, TimeUnit.MILLISECONDS);
                        OkGo okGo = OkGo.getInstance().init(getApplication());
                        okGo.setOkHttpClient(builder.build()).setCacheMode(CacheMode.NO_CACHE).setCacheTime(-1L).setRetryCount(0);

                        RequestBean requestBean = new RequestBean();
                        requestBean.setHeader(new HeaderBean("GoldenSampleTestDataCheck"));
                        requestBean.setBody(map);
                        BaseRequest request = new BaseRequest();
                        request.setRequest(requestBean);

                        Map<String, String> map1 = new HashMap<>();

                        map1.put("requestMessage", StringEscapeUtils.unescapeJson(new Gson().toJson(request)));
                        map1.put("timeOut", "5000");

                        FreeApi_LogUtils.saveErrorMessages("http://" + Constant.REQUEST_URL_DEBUG + "/api/" + "GoldenSampleTestDataCheck", "请求地址");
                        FreeApi_LogUtils.saveErrorMessages(map.toString(), "请求json");

                        ((PostRequest) ((PostRequest) okGo.post("http://" + Constant.REQUEST_URL_DEBUG + "/api/" + "GoldenSampleTestDataCheck").tag(this)).params(map1, new boolean[]{true})).execute(callBack);
                    }
                });
                break;
            case R.id.flMark:
//                if (mMarkPop != null) {
//                    if (mMarkPop.isShowing()) {
//                        mMarkPop.dismiss();
//                    }
//                } else {
                    mMarkPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flMark.getWidth(), testDataList, ivMark, (codeS, i) -> {
                        tvMark.setText(codeS);
                        FreeUI_EntityCallBack<BaseResponseBean<GoldenSampleTestDataEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<GoldenSampleTestDataEntity>>
                                (new TypeToken<BaseResponseBean<GoldenSampleTestDataEntity>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<GoldenSampleTestDataEntity>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                    ArrayList<String> strings = new ArrayList<>();
                                    for (GoldenSampleTestDataEntity.GoldenSampleCfgEntity data:response.body().getResponse().getBody().getGoldenSampleCfgs()){
                                        strings.add(data.getSampleNO());
                                    }
                                    mGoldenSmapleAdapter.setDataList(strings);
                                    mGoldenSmapleAdapter.setNewData(response.body().getResponse().getBody().getDatas());
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<GoldenSampleTestDataEntity>> response) {
                                super.onError(response);
                                loadError(response.getException(),"GetGoldenSampleTestData");
                            }
                        };
                        JsonObject map = new JsonObject();
                        for (GoldenSampleTestDataEntity.DataEntity dataEntity : dataEntities) {
                            if (dataEntity.getTestType().equals(codeS)){
                                map.addProperty("TestRecID", dataEntity.getTestRecId());
                            }
                        }

                        NetUtils.requestPostNet("IF.GetGoldenSampleTestData", "GetGoldenSampleTestData", this, map, callBack);
                    });
//                }
                FreeApi_PopUtils.setArrowShow(ivMark);
                mMarkPop.showAsDropDown(flMark, 0, 0);
                break;

        }

    }
}
